﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using DataCenter.Interface.Model;

namespace DataCenter.Utility
{
    public partial class XmlEditForm : Form
    {
        private XmlEditForm()
        {
            InitializeComponent();
        }
        public XmlEditForm(ComponentEntity entity)
            :this()
        {
            this.Entity = entity;
        }
        private ComponentEntity Entity;

        private void XmlEditForm_Load(object sender, EventArgs e)
        {
            SetComponentConfig(Entity.ComponentConfig);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtComponentConfig.Text))
            {
                Entity.ComponentConfig = "<CONFIG />";
            }
            else
            {
                if (CheckXml())
                {
                    Entity.ComponentConfig = txtComponentConfig.Text;

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
        }

        private bool CheckXml()
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(txtComponentConfig.Text);

                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }
        }
        private void SetComponentConfig(string xmlStr)
        {
            txtComponentConfig.Text = XmlFormat(xmlStr);
        }
        private string XmlFormat(string xmlStr)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlStr);

            StringBuilder builder = new StringBuilder();
            StringWriter writer = new StringWriter(builder);

            XmlTextWriter xmlWriter = new XmlTextWriter(writer);
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.Indentation = 1;
            xmlWriter.IndentChar = '\t';
            xmlDoc.WriteTo(xmlWriter);
            xmlWriter.Close();

            return builder.ToString();
        }
    }
}
